
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 二叉树中序遍历，左中右
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function (root) {
    let arr = [];

    getTreeNodeVal(root, arr);

    return arr
};

function getTreeNodeVal(root, arr) {
    if (root === null) return
    // 先递归左子树，一直到底，为null，return后放值
    getTreeNodeVal(root.left, arr)
    arr.push(root.val)
    getTreeNodeVal(root.right, arr)
}


/**
 * 迭代法，通过栈存储已迭代左子节点的父节点，然后出栈时遍历父节点的右子节点
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
    if (root === null) return []

    let temp = root,
        stack = [],
        res = [];

    while (stack.length > 0 || temp !== null) {
        while (temp) {
            stack.push(temp)
            temp = temp.left
        }
        let node = stack.pop()
        res.push(node.val)
        temp = node.right
    }
    
    return res
};

function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val)
    this.left = (left === undefined ? null : left)
    this.right = (right === undefined ? null : right)
}

let a = new TreeNode(1)
a.right = new TreeNode(2)
a.right.left = new TreeNode(3)

console.log(inorderTraversal(a));